"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 文件目录
Case Name   : 配置pg_hba文件远程连接方式为reject，用普通用户连接
Create At   : 2020/07/21
Owner       : @li-xin12345
Description :
    1. 创建普通用户
    2. 设置pg_hba.conf.conf文件中的METHOD为reject
    3. 重启数据库使配置文件生效
    4. 用配置文件中配置的host连接本机普通用户
    5. 删除普通用户用户
Expect      :
    1. 成功
    2. 成功
    3. 成功
    4. 合理报错
    5. 成功
History     : Modified by @li-xin12345 at 2023.5.29 研发代码变更，优化用例
"""

import os
import unittest
from yat.test import Node
from testcase.utils.CommonSH import *
import sys

from yat.test import macro
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

logger = Logger()
sys.path.append(sys.path[0] + "/../")


class IndexFileDamaged(unittest.TestCase):
    sh_primy = CommonSH('PrimaryDbUser')
    sh_stadb = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.rootNode = Node('PrimaryRoot')
        self.primaryNode = Node(node='PrimaryDbUser')
        self.otherNode = Node(node='remote_PrimaryDbUser')
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
        self.native_host = self.primaryNode.ssh_host
        self.REMOTE_HOST = self.otherNode.ssh_host
        self.REMOTE_ENV = macro.REMOTE_ENV
        self.native_db_name = self.primaryNode.db_name
        self.native_port = self.primaryNode.db_port
        self.native_name = self.primaryNode.ssh_user
        self.passwd_initial = macro.PASSWD_INITIAL
        self.passwd_replace = self.primaryNode.db_password
        self.Constant = Constant()
        self.err_msg = 'failed to connect'

        msg = self.sh_primy.executeGsguc('reload',
                                         self.Constant.GSGUC_SUCCESS_MSG,
                                         'password_encryption_type=2')
        self.assertTrue(msg)

    def test_Index_file_damaged(self):
        # 在本机创建普通用户
        logger.info('-----step1：在本机创建普通用户；expect:成功-----')
        sql_cmd = f'''
                    drop user if exists jack ;
                    create user jack identified by '{self.passwd_initial}';
                    alter user jack identified by '{self.passwd_replace}' replace '{self.passwd_initial}';
                    grant all privileges to jack;
                    '''
        excute_cmd = f'''
                    source {self.DB_ENV_PATH} ;
                    gsql -d {self.primaryNode.db_name} -p {self.primaryNode.db_port} -c "{sql_cmd}"
                    '''
        logger.info(excute_cmd)
        msg = self.primaryNode.sh(excute_cmd).result()
        logger.info(msg)
        self.assertIn(self.Constant.CREATE_ROLE, msg)

        # 改变远程连接方式
        logger.info('-----step2：设置pg_hba.conf.conf文件中的METHOD为reject；'
                    'expect:成功-----')
        excute_cmd = f'''
                        source {self.DB_ENV_PATH};
                        gs_guc set -N all -I all -h "host    all    jack    {self.REMOTE_HOST}/32    reject";
                    '''
        logger.info(excute_cmd)
        msg = self.primaryNode.sh(excute_cmd).result()
        logger.info(msg)
        self.assertIn(self.Constant.GSGUC_SUCCESS_MSG, msg)

        # 重启使参数生效
        logger.info('-----step3：重启数据库使参数生效；expect:成功-----')
        is_stopped = self.sh_primy.stopDbCluster()
        self.assertTrue(is_stopped)
        is_started = self.sh_primy.startDbCluster()
        self.assertTrue(is_started)

        # 用配置文件中配置的host连接本机普通用户
        logger.info('-----step3：用配置文件中配置的host连接本机普通用户；'
                    'expect:合理报错-----')
        excute_cmd = f'''
                        source {self.REMOTE_ENV};
                        gsql -d {self.native_db_name} -h {self.native_host} -p {self.native_port} -U 'jack' -W '{self.passwd_replace}' -l;
                        '''
        logger.info(excute_cmd)
        msg = self.otherNode.sh(excute_cmd).result()
        logger.info(msg)
        self.assertIn(self.err_msg, msg)

        # 删除新建普通用户
        logger.info('-----step4：删除新建普通用户expect:成功')
        sql_cmd = "drop user jack;"
        excute_cmd = f'''
                        source {self.DB_ENV_PATH};
                        gsql -d {self.primaryNode.db_name} -p {self.primaryNode.db_port} -c "{sql_cmd}";
                       '''
        logger.info(excute_cmd)
        msg = self.primaryNode.sh(excute_cmd).result()
        logger.info(msg)

    def tearDown(self):
        logger.info('------------------------后置处理-------------------------')
        try:
            db_status = self.sh_primy.getDbInstanceStatus()
            logger.info(db_status)
            if db_status:
                pass
            else:
                is_started = self.sh_primy.startDbCluster()
                self.assertTrue(is_started)
                logger.info(f'{is_started}')
                logger.info(f'db_status: {is_started}')
        finally:
            excute_cmd = f'''
                                    source {self.DB_ENV_PATH};
                                    gs_guc set -N all -I all -h "host    all    jack    {self.REMOTE_HOST}/32";
                                '''
            logger.info(excute_cmd)
            msg = self.primaryNode.sh(excute_cmd).result()
            logger.info(msg)

            msg = self.sh_primy.executeGsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'password_encryption_type=1')
            logger.info(msg)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
